package es.sergionadal.mvc.multimedia;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

public class SoundPlayer {

	private MediaPlayer mediaPlayer;
	private boolean estaSonando = false;
	private boolean enLoop = false;

	public SoundPlayer(Context ctx, Uri uri) {
		mediaPlayer = MediaPlayer.create(ctx, uri);
		setListener();
	}

	public SoundPlayer(Context ctx, int id) {
		mediaPlayer = MediaPlayer.create(ctx, id);
		setListener();
	}

	private void setListener() {
		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						estaSonando = false;
						if (enLoop) {
							mp.start();
						}
					}
				});
	}

	public synchronized void play() {
		if (estaSonando)
			return;
		if (mediaPlayer != null) {
			estaSonando = true;
			mediaPlayer.start();
		}
	}

	public synchronized void stop() {
		try {
			enLoop = false;
			if (estaSonando) {
				estaSonando = false;
				mediaPlayer.pause();
			}
		} catch (Exception e) {
			System.err.println("Error");
		}
	}

	public synchronized void loop() {
		enLoop = true;
		estaSonando = true;
		mediaPlayer.start();
	}

	public void release() {

		if (mediaPlayer != null && !estaSonando) {
			while (mediaPlayer.isPlaying())
				;
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}
}
